package com.moefor.clover.dao.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.moefor.clover.dao.GoodsDao;
import com.moefor.clover.model.Goods;
import com.moefor.clover.model.Market;
import com.moefor.clover.model.enums.StateOfGoods;
@Repository
public class GoodsDaoImpl extends BaseDaoImpl<Goods> implements GoodsDao{

	@Override
	public Set<Goods> search(String keyword, Integer pageNum, Integer pageSize, Set<Market> marketSet, StateOfGoods state) {
		// TODO Auto-generated method stub
		StringBuffer hql = new StringBuffer();
		if(marketSet == null) return null;
		
		hql.append("SELECT distinct(g) FROM Goods g JOIN g.marketItems m WHERE  g.state = ? AND g.name LIKE ?  AND (1=2");
		for(int i = 0; i<marketSet.size(); i++){
			hql.append(" OR m.id=?");
		}
		hql.append(")");
		
		Query query = getSession().createQuery(hql.toString());
		query.setString(1, "%" + keyword +"%");
		query.setInteger(0, state.ordinal());
		int i = 2;
		for(Market m: marketSet){
			query.setInteger(i++, m.getId());
		}
		
		query.setFirstResult((pageNum-1)*pageSize); 
		query.setMaxResults(pageSize); 
		
		Set<Goods> goods = new HashSet<Goods>();
		goods.addAll(query.list());
		if(goods.isEmpty()) goods = null;
		return goods;
	}

	@Override
	public Set<Goods> getByOwner(int ownerId) {
		// TODO Auto-generated method stub
		Query query = getSession().createQuery("SELECT g FROM Goods g WHERE g.owner.id=?");
		query.setInteger(0, ownerId);
		Set<Goods> goods = new HashSet<Goods>();
		goods.addAll(query.list());
		if(goods.isEmpty()) goods = null;
		return goods;
	}

	@Override
	public Set<Goods> searchByMarket(String marketName, Integer pageNum, Integer pageSize, StateOfGoods state) {
		// TODO Auto-generated method stub
		Query query = getSession().createQuery("SELECT g FROM Goods g JOIN g.marketItems m WHERE m.name LIKE ? AND g.state=?");
		query.setString(0, "%" + marketName + "%");
		query.setInteger(1, state.ordinal());
		query.setFirstResult((pageNum-1)*pageSize); 
		query.setMaxResults(pageSize); 
		Set<Goods> goods = new HashSet<Goods>();
		
		goods.addAll(query.list());
		if(goods.isEmpty()) goods = null;
		return goods;
	}

	@Override
	public Set<Goods> searchByMarket(int marketId, Integer pageNum, Integer pageSize, StateOfGoods state) {
		// TODO Auto-generated method stub
		Query query = getSession().createQuery("SELECT g FROM Goods g JOIN g.marketItems m WHERE m.id=? AND g.state=?");
		query.setInteger(0, marketId);
		query.setInteger(1, state.ordinal());
		query.setFirstResult((pageNum-1)*pageSize); 
		query.setMaxResults(pageSize); 
		Set<Goods> goods = new HashSet<Goods>();
		goods.addAll(query.list());
		if(goods.isEmpty()) goods = null;
		return goods;
	}

}
